 
var pageContext = new PageContextDatatable(settings||{});
pageContext.setting.canPage = false;

var pageContextTree = new PageContextTree(settings||{});
pageContextTree.hasInstance = false;
pageContextTree.removeItemAfter = function(ids){
	 if(!isNaN(ids)){
		 pageContext.setDeleteClass($("#"+pageContext.setting.tableId+"_tr_"+ids),true);
	 }else{
		var array = ids.split(",");
		for (x in array)
		{
			var id = array[x];
			pageContext.setDeleteClass($("#"+pageContext.setting.tableId+"_tr_"+id),true);
		}
	}
}; 	
pageContext.formInit = function(layero,index,type){
	layero.find('select').each(function(){
		var novalid = $(this).attr("novalid");
		if(novalid!="true"){
			 
		}
	  });
}; 	
pageContext.toAddCheck = function(data){
	var nodes = pageContextTree.getSelectedNodes();
	var selected = false;
	for(index in nodes){
		var node = nodes[index];
		if(node){
			return true;
		}
	}
	if(pageContextTree.hasInstance){
		alert("请选择系统或上级角色！");
		return false;
	}else{
		return true;
	}
};
pageContext.updateItemAfter = function(result,para){
	pageContextTree.reload();
};
pageContext.addItemAfter = function(result,para){
	pageContextTree.reload();
};
pageContext.deleteItemAfter = function(id){
	pageContextTree.reload();
};
pageContext.removeItemAfter = function(id){
	pageContextTree.reload();
};
pageContext.renderAddPageOther = function(layero,data,option){
	var name = "pId";
	var nodes = pageContextTree.getSelectedNodes();
	var selected = false;
	for(index in nodes){
		var node = nodes[index];
		if(node){
			var value = node.id;
			var instanceId = null;
			if(pageContextTree.hasInstance && node.id==null){
				instanceId = node.instanceId;
			}else{
				instanceId = node.instanceId;
				layero.find("span[name='pName']").text(node.name);
				layero.find("input[name='"+name+"']").attr("oldval",value).val(value);
				layero.find("input[name='remark']").attr("oldval",value).val(node.remark);
				tvc.changeDefaultValue(layero.find("input[name='"+name+"']").get(0));
			}
			if(instanceId!=null){
				layero.find("form").append('<input type="hidden" name="instanceId" value="'+instanceId+'">')
				var sysFlag = layero.find("select[name='instanceId']")
				$(sysFlag).attr("name","").attr("novalid","true").closest("div").hide();
				sysFlag.attr("oldval",instanceId).val(instanceId);
				try{
					sysFlag.select2("val",instanceId)
				}catch(e){}
				tvc.changeDefaultValue(sysFlag.get(0));
			}
		}
	}
};
pageContext.renderUpdatePageOther = function(layero,data,option){
	var name = "pId";
	var value = data.pId;
	var node = pageContextTree.getNode(value);
	if(node){
		layero.find("span[name='pName']").text(node.name);
		layero.find("input[name='"+name+"']").attr("oldval",value).val(value);
		layero.find("input[name='remark']").attr("oldval",value).val(node.remark);
		tvc.changeDefaultValue(layero.find("input[name='"+name+"']").get(0));
		layero.find("select[name='instanceId']").attr("novalid","true").closest("div").hide();
	}
};

/**资源树**/  
var tree_setting = {
		async: {
			enable: true,
			type: "get",
			url: window.global.getFinalUrl(window.global.ctx+"/auth/role/query?_style=list"),
			otherParam: {'hasInstance':window.global.hasInstance,"noPage":"true"},
			autoParam: ["instanceId","id=pId"]
		},
		view: {
			addHoverDom: null,
			removeHoverDom: null,
			selectedMulti: false
		},
		check: {
			enable: true
			,chkboxType :{ "Y" : "", "N" : "" } 
		},
		data: {
			simpleData: {
				enable: true
			}
			,key: {
				url: ""
			}
		},
		data: {
			simpleData: {
				enable: true
			}
		} 
		,edit: {
			enable: true,
			editNameSelectAll: true,
			showRemoveBtn: null,
			showRenameBtn: null
		}
		,callback: {
			 onClick: zTreeOnClick
			,onCheck: zTreeOnCheck
			,onDrop: zTreeOnDrop
			,beforeDrop: zTreeBeforeDrop
			,onAsyncSuccess: zTreeOnAsyncSuccess
		}
};
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	var $num = $("#searchForm").find("input[name='num']")
	var num = $num.val();
	var node  = pageContextTree.getNodeFromParent("num",num,treeNode)
	if(node){
		pageContextTree.selectNode(node.id);
	}else{
		$num.val("");
	}
	pageContext.search();
};
function zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
	if(moveType!=null && treeNodes){
		for(var i in treeNodes){
			var node = treeNodes[i];
			var pNode = null;
			var canMove = true;
			if("inner"==moveType){
				pNode = targetNode;
			}else{
				if(targetNode){
					pNode = targetNode.getParentNode();
				}
			}
			if((node.type && node.type=="instance")
				|| (targetNode && node.instanceId!=targetNode.instanceId)){
				canMove = false;
			}
			if(canMove){
				return pageContextTree.move(node,pNode);
			}
		}
	}
    return false;
};
function zTreeOnDrop(event, treeId, treeNodes, targetNode, moveType) {
	if(moveType!=null && treeNodes){
		for(var i=0;i<treeNodes.length;i++){
			var node = treeNodes[i];
			pageContextTree.updateOrderNum(node.getNextNode(),parseInt(node.getIndex(),10)+1);
		}
	}
	pageContextTree.reload();
};
pageContextTree.move = function(node,pNode){
	var ok = false;
	if(node){
		var data = {};
		data.id = node.id;
		if(pNode){
			data.pId = pNode.id;
		}
		if(node.getPreNode()){
			data.orderNum = node.getPreNode().getIndex();
		}else{
			data.orderNum = 1;
		}
		$.ajax({
			url:window.global.getFinalUrl(window.global.ctx+"/auth/role/move")
			,async:false
			,type: "post"
			,data:data
			,dataType:"json"
			,success:function(result){
				if(result.status==200){
					ok = true;
				}else{
					ok = false;
				}
			}
		    ,error: function(XMLHttpRequest, textStatus, errorThrown) {
		    	ok = false;
		    }
		});
	}
	return ok;
}
function updateOrderNum1(node,index){
	console.log(node)
	if(node){
		updateOrderNum1(node.getNextNode(),index++);
	}
}
pageContextTree.updateOrderNum = function(node,index){
	var ok = true;
	if(node){
		var data = {};
		data.id = node.id;
		data.pId = node.pId;
		data.orderNum = index;
		$.ajax({
			url:window.global.getFinalUrl(window.global.ctx+"/auth/role/move")
			,async:false
			,type: "post"
			,data:data
			,dataType:"json"
			,success:function(result){
				if(result.status==200){
					pageContextTree.updateOrderNum(node.getNextNode(),index++);
					ok = true;
				}else{
					ok = false;
				}
			},error: function(XMLHttpRequest, textStatus, errorThrown) {
				ok = false;
			}
		});
	}
	return ok;
}
function zTreeOnCheck(event, treeId, treeNode) {
	$($($("#"+pageContext.setting.tableId+"_tr_"+treeNode.id).find("td").get(0)).find("input")).prop("checked",treeNode.checked);
};
function zTreeOnClick(event, treeId, treeNode) {
	$("#searchForm").find("input[name='num']").val("");
	var sysFlag = $("#searchForm").find("select[name='instanceId']");
	sysFlag.val("").trigger("change");
	var nodes = pageContextTree.getNodes();
	for(var index in nodes){
		var node = nodes[index];
		if(treeNode.type && treeNode.type=="instance"){
			if(node.type && node.type=="instance"
				&& node.instanceId ==treeNode.instanceId){
				if(node.selected){
					node.selected = false;
					pageContextTree.treeObj.cancelSelectedNode(node,false,false);
				}else{
					if(node){
						node.selected = true;
						pageContextTree.treeObj.selectNode(node,false,false);
						if(node.hasOwnProperty("pId")){
							pageContextTree.expandNode(node.pId);
						}
						var allNodes = pageContextTree.getNodes();
						var id = null;
						for(var index in allNodes){
							if(allNodes[index].id==null){
								if(allNodes[index].type && allNodes[index].type=="instance"
									&& allNodes[index].instanceId !=node.instanceId){
									allNodes[index].selected = false;
									pageContextTree.treeObj.cancelSelectedNode(allNodes[index],false,false);
								}
							}else{
								if(allNodes[index].id != id){
									allNodes[index].selected = false;
									pageContextTree.treeObj.cancelSelectedNode(allNodes[index],false,false);
								}
							}
						}
					}					
					sysFlag.val(node.instanceId).trigger("change");
				}
				break;
			}
		}else{
			if(node.id==treeNode.id){
				if(node.selected){
					$("#searchForm").find("input[name='num']").val("");
					pageContextTree.cancelSelectedNode(node.id);
				}else{
					pageContextTree.selectNode(node.id);
					$("#searchForm").find("input[name='num']").val(node.num);
					var index = $("#"+pageContext.setting.tableId+"_tr_"+node.id).attr("rowIndex");
				}
				break;
			}
		}
	}
	pageContext.search();
};

pageContextTree.reload = function(){
	var nodes = pageContextTree.getNodesFromParent("type","instance",null)
	if(nodes && nodes.length>0){
		pageContextTree.hasInstance = true;
		for(var i in nodes){
			var obj = nodes[i];
			pageContextTree.treeObj.reAsyncChildNodes(obj, "refresh");
		}
	}else{
		pageContextTree.treeObj.reAsyncChildNodes(null, "refresh");
	}
}
pageContextTree.load = function(){
	$.ajax({
		url:window.global.getFinalUrl(window.global.ctx+"/sys/instance/list")
		,async:true
		,type: "get"
		,dataType:"json"
		,success:function(result){
			if(result.status==200){
				var list = result.data.list;
				var array = null;
				if(list && list.length>1){
					array = [];
					for(var i in list){
						var obj = list[i];
						var item = {};
						item.name = obj.nameStr;
						item.id = null;
						item.type = "instance";
						item.instanceId = obj.id;
						item.title = obj.remark;
						item.nocheck = true;
						item.isParent = true;
						array.push(item);
					}
				}else if(list && list.length==1){
					var obj = list[0];
					tree_setting.async.url= window.global.addPara(tree_setting.async.url,"instanceId",obj.id,true);
				}
			
				pageContextTree.initTree($("#treeForm"+" .ztree"),array, tree_setting )
		    	if(array != null){
		    		pageContextTree.reload();
				}
				ok = true;
			}else{
				ok = false;
			}
		}
	    ,error: function(XMLHttpRequest, textStatus, errorThrown) {
	    	ok = false;
	    }
	});
}
pageContext.getCheckedIds = function() {//获取表格选中的id
	var ids = [];
	 var nodeids = pageContextTree.getCheckedNodes();
	 if(nodeids){
		for(var i = 0; i < nodeids.length; i++) {
			ids.push(nodeids[i].id);
		}
	 }
	 var records = pageContext.getCheckedRecords();
	 if(records){
		for(var i = 0; i < records.length; i++) {
			ids.push(pageContext.gridObj.getRecordIndexValue(records[i], 'id'));
		}
	 }
	 return ids.join(",");
};
pageContext.renderAfterEventOther = function() {
	$('#'+pageContext.setting.tableId+' > tbody > tr').on('click', function(e){
		 if($(this).hasClass("selected")){
			 pageContextTree.selectNode($(this).attr("val"))
		 }else{
			 pageContextTree.cancelSelectedNode($(this).attr("val"))
		 }
    });
} 

/**
 * 渲染tree
 */
pageContext.afterRenderGrid = function(gridData){
	if(!pageContext.passiveInvoke){
		 pageContextTree.reload();
	 }
	 pageContext.passiveInvoke = true;
	//pageContextTree.initTree($("#treeForm"+" .ztree"),gridData.data, tree_setting )
};

pageContext.getCheckedIds = function() {//获取表格选中的id
	 var ids = [];
	 var nodeids = pageContextTree.getCheckedNodes();
	 if(nodeids){
		for(var i = 0; i < nodeids.length; i++) {
			ids.push(nodeids[i].id);
		}
	 }
	 var records = pageContext.getCheckedRecords();
	 if(records){
		for(var i = 0; i < records.length; i++) {
			ids.push(pageContext.gridObj.getRecordIndexValue(records[i], 'id'));
		}
	 }
	 return ids.join(",");
};
pageContext.renderAfterEventOther = function() {
	$('#'+pageContext.setting.tableId+' > tbody > tr').on('click', function(e){
		 if($(this).hasClass("selected")){
			 pageContextTree.selectNode($(this).attr("val"))
		 }else{
			 pageContextTree.cancelSelectedNode($(this).attr("val"))
		 }
    });
}
pageContext.getOtherOperBtn = function(id,label,record){
	var html = [];	
	if(pageContext.setting.canShowPower){
		html.push('<li>');
		html.push('<a href="javacript:void(0)" label="'+label+'"  url="'+window.global.getFinalUrl(window.global.ctx+'/auth/roleauth/toedit?roleId='+record.id)+'" instance="'+record.instanceId+'" val="'+id+'" class="tooltip-success propBtn" data-rel="tooltip" title="权限">');
		html.push('<span class="primary">');
		html.push('<i class="ace-icon fa fa-wrench bigger-120"></i>');
		html.push('</span>');
		html.push('</a>');
		html.push('</li>');
	}
	if(pageContext.setting.canAuthorize && pageContext.canAuthorizeTree(record.instanceId)){
		html.push('<li>');
		html.push('<a href="javacript:void(0)" label="'+label+'"  url="'+window.global.getFinalUrl(window.global.ctx+'/auth/roleauthorize/toedit?roleId='+record.id)+'"  instance="'+record.instanceId+'" val="'+id+'" class="tooltip-success authorizeBtn" data-rel="tooltip" title="授权">');
		html.push('<span class="green">');
		html.push('<i class="ace-icon fa fa-cog bigger-120"></i>');
		html.push('</span>');
		html.push('</a>');
		html.push('</li>');
	}
	return html.join("");
}
pageContext.getOtherPingPuOperBtn = function(id,label,record){
	var html = [];
	if(pageContext.setting.canShowPower){
		html.push('<button class="btn btn-xs btn-primary propBtn" label="'+label+'"  url="'+window.global.getFinalUrl(window.global.ctx+'/auth/roleauth/toedit?roleId='+record.id)+'" instance="'+record.instanceId+'" val="'+id+'" title="权限">');
		html.push('<i class="ace-icon fa fa-wrench bigger-120"></i>');
		html.push('</button>');
	}
	if(pageContext.setting.canAuthorize && pageContext.canAuthorizeTree(record.instanceId)){
		html.push('<button class="btn btn-xs btn-info authorizeBtn" label="'+label+'"  url="'+window.global.getFinalUrl(window.global.ctx+'/auth/roleauthorize/toedit?roleId='+record.id)+'" instance="'+record.instanceId+'" val="'+id+'" title="授权">');
		html.push('<i class="ace-icon fa fa-cog bigger-120"></i>');
		html.push('</button>');
	}
	return html.join("");
}

pageContext.canAuthorizeTree = function(instance){
	var all = false;
	var ok = false;
	if(instance && instance!="undefined"){
		if(instance==window.global.msSysId){
			all = true;
			ok = true;
		}
	}else{
		all = true;
		ok = true;
	}
	return all;
}
pageContext.renderAfterEventOther = function(){
	$('#'+pageContext.setting.tableId+' >tbody').on("click","tr > td .propBtn",function(e){
		e.stopPropagation();
		var val = $(this).attr("val");
		 var label = $(this).attr("label");
		 var instance = $(this).attr("instance");
	      var url = ($(this).attr("url"));
		 url = window.global.addPara(url,"instanceId",instance,true);
		 load(url,"page-content",true,"角色【"+label+"】"+"权限",function(){
				
		 });
		 return false;
	});
	$('#'+pageContext.setting.tableId+' >tbody').on("click"," tr > td .authorizeBtn",function(e){
		e.stopPropagation();
		var val = $(this).attr("val");
		 var label = $(this).attr("label");
		 var instance = $(this).attr("instance");
	     var url = ($(this).attr("url"));
		 url = window.global.addPara(url,"instanceId",instance,true);
		 load(url,"page-content",true,"角色【"+label+"】"+"可授权资源",function(){
				
		 });
		 return false;
	});
}
function otherPageInit(){
	var h = document.body.clientHeight;
	h = h-$("#treeDiv").offset().top;
    $("#treeDiv").height(h);
}
pageContext.toAdd = function(option){
	var action = window.global.getFinalUrl(pageContext.setting.toAddUrl);
	var nodes = pageContextTree.getSelectedNodes();
	var selected = false;
	for(var index in nodes){
		var node = nodes[index];
		if(node){
			var value = node.id;
			var instanceId = null;
			if(pageContextTree.hasInstance && node.id==null){
				instanceId = node.instanceId;
			}else{
				instanceId = node.instanceId;
			} 
			if(!instanceId){
				instanceId = null;
			}
			if(!(value==null || value=="null")){
				action = window.global.addPara(action,"pId",value,true)
				action = window.global.addPara(action,"pName",node.name,true)
			}
			action = window.global.addPara(action,"instanceId",instanceId,true)
		}
	}
	load(action,"page-content",true,"新增"+pageContext.modelName,function(){
		
	});
}
pageContext.toDetail = function(id,data){
	var action = window.global.getFinalUrl(pageContext.setting.toDetailUrl);
	action = window.global.addPara(action,"id",id,true)
	load(action,"page-content",true,pageContext.modelName+"详情",function(){
		
	});
}
pageContext.toUpdate = function(id,data){
	var action = window.global.getFinalUrl(pageContext.setting.toUpdateUrl);
	action = window.global.addPara(action,"id",id,true)
	load(action,"page-content",true,"修改"+pageContext.modelName,function(){
		
	});
}
pageContext.resetFormAfter = function (){
	$("#searchForm select").val(null).trigger("change"); 
}
$(function(){
	 pageContextTree.load();
	 pageContext.init({pageAll:true});

	 $(document).find("input").each(function(){
		 $(this).attr("autocomplete","off");
	 });
    var layero = $("#searchForm");
	layero.find('select[novalid!="true"]').each(function(){
		var novalid = $(this).attr("noconvert");
		if(novalid!="true"){
			var $span = layero.find(this).select2({
	            language: "zh-CN"
		            ,matcher:select2Matcher})
	            .next("span")
	            ;
		}
	  });
})
